const app = getApp();
Page({
  data: {
    hidden: false, //加载
    outline: false, //有无网络
    index: 0,
    todos: [],//
    phone: '',
    token: '',
    imgUrls:[],
    pay_info: {
      ucode: '',
      from: '摩倍',
      goods: '足浴按摩',
      money: '',
      time: '',
      deviceid: '',
    },
    device_str: {
      time: "",
      deviceid: '',
      tradeNO: ''
    },
    sel: 0,
    deviceid: "",
    hasNetworkType: false,
    status1: 1,
    status: ''
  },
  onLoad(query) {
  },
  onReady() {

  },
  onShow() {
    var that = this;
    my.getNetworkType({
      success: (res) => {
        if (res.networkAvailable) {
          that.setData({
            outline: false,
            todos: []
          })
          that.getToken()
        } else {
          that.setData({
            outline: true
          })
        }
      }
    })
  },
  // 扫码
  scan() {
    my.scan({
      type: 'qr',
      success: (res) => {
        var str = JSON.stringify(res.code)
        this.setData({
          deviceid: str.substring(str.length - 12, str.length - 1),
        })
        app.issaoma = true;
      },
    });
  },
  onHide() {
    // 页面隐藏
  },
  onUnload() {
    // 页面被关闭
  },
  onTitleClick() {
    // 标题被点击
  },
  onPullDownRefresh() {

  },
  onReachBottom() {
    // 页面被拉到底部
  },
  onShareAppMessage() {
    // 返回自定义分享信息
    return {
      title: 'My App',
      desc: 'My App description',
      path: 'pages/index/index',
    };
  },
  //获取页面信息
  getLunbo: function() {
    var that = this;
    my.httpRequest({ // 调用自己的服务端接口，让服务端进行后端的授权认证，并且种session，需要解决跨域问题
      url: 'https://www.tiantong369.com/crm/index/', // 该url是自己的服务地址
      method: 'POST',
      headers: {
        'x-access-token': that.data.token
      },
      data: {},
      dataType: 'json',
      success: (res) => {// 成功获取订单号
        console.log(res)
        if (res.data.status == 200) {
          var img = [];
          for (var i = 0; i < res.data.app.banner.length; i++) {
            img.push(res.data.app.banner[i].imgurl)
          }
          that.setData({
            phone: res.data.app.phone,
            imgUrls: img,
          })

          console.log(that.data.imgUrls)
        }


      },
      fail: (res) => {
        console.log('GetEmpPrice:', res)
      },
    });
  },
  // 体验码启动
  code() {
    if (app.issaoma == false) {
      my.alert({ content: '未检测到设备，请点击右上角的扫一扫，选择正确的二维码扫描...' });
      return;
    }
    my.navigateTo({ url: '../Pay/pay' });
  },
  radioChange: function(e) {
    var that = this;
    var items = that.data.todos;
    for (var i = 0; i < items.length; i++) {
      if (e.detail.value == i) {
        items[i].checked = true;
      } else {
        items[i].checked = false;
      }
    }
    that.data.index = e.detail.value
    that.data.pay_info.money = that.data.todos[e.detail.value].price
    that.data.pay_info.time = parseInt(that.data.todos[e.detail.value].second)
    that.data.pay_info.deviceid = that.data.deviceid
    that.data.device_str.time = parseInt(that.data.todos[e.detail.value].second)
  },
  getToken() {
    this.setData({
      todos: [],
      deviceid: app.deviceid,
    })
    // 获取token
    my.getAuthCode({
      scopes: 'auth_user', //授权类型，默认auth_base(静默授权)，支持auth_base/auth_user(主动授权)
      success: (res) => {
        if (res.authCode) { // 认证成功
          my.httpRequest({ // 成功之后调用后台开启设备接口
            url: 'https://www.tiantong369.com/gettoken',
            method: 'POST',
            data: res.authCode,
            success: (res) => {
              if (res.data.status == 200) {
                this.setData({
                  token: res.data.token,
                  deviceid: this.data.deviceid,
                  hidden: true,
                })
                this.getLunbo()

                // 页面加载
                var obj = { deviceid: this.data.deviceid }
                my.httpRequest({ // 调用自己的服务端接口，让服务端进行后端的授权认证，并且种session，需要解决跨域问题
                  url: 'https://www.tiantong369.com/crm/GetEmpPrice/', // 该url是自己的服务地址
                  method: 'POST',
                  headers: {
                    'x-access-token': res.data.token
                  },
                  data: obj,
                  dataType: 'json',
                  success: (res) => {// 成功获取订单号
                    var that = this;
                    that.setData({
                      hidden: false,
                    })
                    if (res.data.status == 200) {
                      var arr = that.data.todos;
                      for (var i = 0; i < res.data.data.length; i++) {
                        arr.push(res.data.data[i])
                      }
                      arr[1].checked = true;
                      that.setData({
                        todos: arr,
                      })
                      that.data.pay_info.money = that.data.todos[1].price
                      that.data.device_str.time = parseInt(that.data.todos[1].second)
                      that.data.pay_info.time = parseInt(that.data.todos[1].second)
                      that.data.pay_info.deviceid = that.data.deviceid
                    } else {
                      my.alert({ content: '' + res.data.err_msg + '' });
                    
                    }


                  },
                  fail: (res) => {
                    console.log('GetEmpPrice:', res)
                  },
                });
              }
            },
            fail: (res) => {
              console.log('fail:', res)
            },
          });
        }
      },

    })
  },
  // 点击付款
  click_pay() {
    var that = this;
    if (app.issaoma == false) {
      my.alert({ content: '未检测到设备，请点击右上角的扫一扫，选择正确的二维码扫描...' });
      return;
    }
    that.setData({
      status1: 1,
    })
    var obj = { deviceid: that.data.deviceid }
    my.httpRequest({ // 调用自己的服务端接口，让服务端进行后端的授权认证，并且种session，需要解决跨域问题
      url: 'https://www.tiantong369.com/crm/senddevicemsg/', // 该url是自己的服务地址
      method: 'POST',
      headers: {
        'x-access-token': that.data.token
      },
      data: obj,
      dataType: 'json',
      success: (res) => {// 成功获取订单号
        if (res.data.status == 200) {
          that.setData({
            hidden: true
          })
          that.startSetInter()
        } else {
          my.alert({ content: '' + res.data.err_msg + '' });
        }

      },
      fail: (res) => {
        console.log('GetEmpPrice:', res)
      },
    })
  },
  startSetInter: function() {
    var that = this;
    var obj = { deviceid: that.data.deviceid }
    console.log('ppp', obj)
    my.httpRequest({ // 调用自己的服务端接口，让服务端进行后端的授权认证，并且种session，需要解决跨域问题
      url: 'https://www.tiantong369.com/crm/GetEmpPrice/', // 该url是自己的服务地址
      method: 'POST',
      headers: {
        'x-access-token': that.data.token
      },
      data: obj,
      dataType: 'json',
      success: (res) => {
        if (res.data.device.status == 1) {
          that.pay();
        } else {
          that.data.status1++
          if (that.data.status1 < 20) {
            setTimeout(function() {
              that.startSetInter();
            }, 1500)
          } else {
            that.setData({
              hidden: false
            })
            my.alert({ content: '设备正在联网，请5秒后扫码重试...' });
            return;
          }
        }
      },
      fail: (res) => {
        console.log('GetEmpPrice:', res)
      },
    })

  },

  pay: function() {
    my.getAuthCode({ // 获取用户code
      scopes: 'auth_user', // 主动授权（弹框）：auth_user，静默授权（不弹框）：auth_base
      success: (res) => {
        if (res.authCode) { // 认证成功
          this.data.pay_info.ucode = res.authCode
          var pay_info = this.data.pay_info;
          my.httpRequest({ // 调用自己的服务端接口，让服务端进行后端的授权认证，并且种session，需要解决跨域问题
            url: 'https://www.tiantong369.com/crm/alipay_createorder/', // 该url是自己的服务地址
            method: 'POST',
            data: pay_info,
            headers: {
              'x-access-token': this.data.token
            },
            success: (res) => {//
              this.setData({ hidden: false })
              if (res.data.status == 200) {
                var that = this;
                that.data.device_str.tradeNO = res.data.data.tradeNo
                that.data.device_str.deviceid = that.data.deviceid
                my.tradePay({// 调用此方法唤起支付宝收银台item
                  tradeNO: res.data.data.tradeNo,
                  success: function(res) {
                    console.log('***+', res)
                    if (res.resultCode != '6001') { // 付款成功
                      my.alert({ content: '设备开启成功' });
                    } else { // 用户点了×，并未付款
                      my.alert({ content: '付款失败' });
                    }
                  },
                  fail: function(res) {
                    // console.log('fail', res)
                  },
                });
              }


            },
            fail: (res) => {
              console.log('fail:', res)
            },
          });
        }
      },
    });
  }
});
